package com.bank.controller;

import com.bank.Utils.StrUtils;
import com.bank.common.JsonResult;
import com.bank.entity.User;
import com.bank.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ProjectName: bankSystem
 * @Author: Jsx
 * @Time: 2020/9/16 8:30
 * @Description:
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询用户信息
     * @param session
     * @return
     */
    @RequestMapping("/query.do")
    @ResponseBody
    public JsonResult getLoginInfo(HttpSession session){
        User u = (User) session.getAttribute(StrUtils.LOGIN_USER);
        //需要再次从数据库查询一遍
        User user = userService.selectByCode(u.getBankCode());

        JsonResult jsonResult = new JsonResult(1,user);

        return jsonResult;
    }

    /**
     * 退出登录
     * @param session
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/logout.do")
    @ResponseBody
    public void logOut(HttpSession session,HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException {
        ////清空session
        session.removeAttribute(StrUtils.LOGIN_USER);

        //清空后，重定向到login.html
        response.sendRedirect("/login.html");
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param session
     * @return
     */
    @RequestMapping("/changepassword.do")
    @ResponseBody
    public JsonResult changePassword(String oldPassword , String newPassword ,HttpSession session,HttpServletResponse response) throws IOException {
        //获取用户信息
        User user = (User) session.getAttribute(StrUtils.LOGIN_USER);

        userService.updatePassword(user.getBankCode() , oldPassword , newPassword);

        return new JsonResult(1,"密码修改成功");
    }

    /**
     * 注册账号
     * @param bankCode
     * @param password
     * @return
     */
    @RequestMapping("/register.do")
    @ResponseBody
    public JsonResult register(String bankCode ,String password){
        User user = new User();
        user.setBankCode(bankCode);
        user.setPassword(password);

        return userService.inserUser(user);
    }
}
